import Taro from '@tarojs/taro'
import { post, get } from './request/request'
import apiUrl from './urls'
import { showModal } from './tools/public'

// 检查当前名片是否被工作交接
function checkWorkHandover(cardDetail, outCardId, options) {
  const inCardId = cardDetail.handoverCardId
  const formData = { inCardId, outCardId }

  get(apiUrl.handoverRecordUrl, formData).then(res => {
    const data = res

    // 非被交接人的好友关系
    if (!data) {
      showModal('提示', `你的专属顾问已更换为${cardDetail.cardName}，将为你跳转到ta的最新名片`, {
        confirmText: '好的',
        showCancel: false,
        success: () => goToNewCard(options, inCardId),
        fail: () => {},
        complete: () => {}
      })
      return
    }

    // 已读
    if (+data.isRead !== 0) {
      goToNewCard(options, inCardId)
      return
    }

    // 标记已读
    post(apiUrl.handoverReadMarkUrl, formData).then(() => {}, () => {})
    showModal(
      '提示',
      `为了提升服务质量，已将原专属顾问“${data.outCardInfo.cardName}”更换为“${data.inCardInfo.cardName}”`,
      {
        showCancel: true,
        confirmText: '去看看',
        cancelText: '以后再说',
        success: r => {
          if (r.confirm) {
            goToNewCard(options, inCardId)
            return
          }

          Taro.reLaunch({
            url: '/pages/load/load'
          })
        },
        fail: () => {},
        complete: () => {}
      }
    )
  }, () => {})
}

function goToNewCard(options, inCardId) {
  const params = {
    ...options,
    cardId: inCardId
  }

  const queryParams = Object.keys(params).map(key => `${key}=${params[key]}`)
  Taro.reLaunch({
    url: `/pages/tabbar/card/card?${queryParams.join('&')}`
  })
}

export default checkWorkHandover
